package kr.co.pension.usr.pe.re.controller;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.co.kiso.usr.utils.SMCommonUtil;
import kr.co.pension.admin.co.ma.service.COMAService;
import kr.co.pension.admin.co.ma.vo.COMAVo;
import kr.co.pension.usr.pe.re.service.ChkAdminService;
import kr.co.pension.usr.pe.re.service.ChkService;
import kr.co.pension.utils.BaseController;
import kr.co.pension.utils.PaginationInfo;

import org.apache.commons.lang.time.FastDateFormat;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * 펜션 예약관리
 * 
 * @author devhw
 * 
 */
@Controller
@RequestMapping("/chkAdm/data/info/*")
public class ChkAdminController extends BaseController {
	@Autowired
	private ChkAdminService service;
	@Autowired
	private ChkService usrService;
	@Autowired
	private COMAService comaService;

	Logger log = Logger.getLogger(getClass());


	@RequestMapping
	public ModelAndView usrList(@RequestParam Map vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		isAdminMember(req,res);
		ModelAndView mav = new ModelAndView();

		COMAVo codeVo = new COMAVo();

		//지역
		codeVo.setCode_p_no("08");
		mav.addObject("cdList1", comaService.coma104Q(codeVo));
		codeVo.setCode_p_no("07");
		mav.addObject("cdList2", comaService.coma104Q(codeVo));
		
		mav.addObject("cdList3", service.adminCode(vo));
		
		if(vo.get("syyyy")!=null && !"".equals(vo.get("syyyy") )){
			vo.put("syyyy", vo.get("syyyy"));
			if(vo.get("smm")!=null && !"".equals(vo.get("smm") )){
				vo.put("syyyy", vo.get("syyyy").toString() +vo.get("smm"));
				if(vo.get("sdd")!=null && !"".equals(vo.get("sdd") )){
					vo.put("syyyy", vo.get("syyyy").toString() +vo.get("sdd"));
				}
			}
		}
		
		if(vo.get("eyyyy")!=null && !"".equals(vo.get("eyyyy") )){
			vo.put("eyyyy", vo.get("eyyyy"));
			if(vo.get("emm")!=null && !"".equals(vo.get("emm") )){
				vo.put("eyyyy", vo.get("eyyyy").toString() +vo.get("emm"));
				if(vo.get("edd")!=null && !"".equals(vo.get("edd") )){
					vo.put("eyyyy", vo.get("eyyyy").toString() +vo.get("edd"));
				}
			}
		}
		
		PaginationInfo pg = new PaginationInfo();
		int currnetPageNo = 1;
		if(vo.get("currentPageNo")!=null && !"".equals( vo.get("currentPageNo"))){
			currnetPageNo = Integer.parseInt( vo.get("currentPageNo").toString());
		}
		pg.setCurrentPageNo(currnetPageNo);
		pg.setParamMap(vo);

		int iCnt = service.usrListCnt(vo);
		
		pg.setTotalRecordCount(iCnt);
		
		vo.put("page", pg);
		if(iCnt>0){
			mav.addObject("list", service.usrList(vo));	
		}
		
		mav.addObject("pageHtml", pg.getToHtml("./usrList.do"));
		mav.addObject("paginationInfo", vo);
		return mav;
	}
	
	@RequestMapping
	public ModelAndView intUsr(@RequestParam Map vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		isAdminMember(req,res);
		ModelAndView mav = new ModelAndView();
		COMAVo codeVo = new COMAVo();
		// 가입사이트
		codeVo.setCode_p_no("05");
		mav.addObject("cd1List", comaService.coma104Q(codeVo));
		
		//등급
		codeVo.setCode_p_no("06");
		mav.addObject("cd2List", comaService.coma104Q(codeVo));

		mav.addObject("cdList3", service.adminCode(vo));
		return mav;
	}

	@RequestMapping
	public ModelAndView insertUsr(@RequestParam Map vo, HttpServletRequest req,@RequestParam String[] hps,
			HttpServletResponse res) throws Exception {
		isAdminMember(req,res);
		ModelAndView mav = new ModelAndView("common/toJson");
		Map jsonMap = new HashMap();
		
		if(hps.length==0){
			jsonMap.put("returnCd", "2");

			mav.addObject("map", jsonMap);
			
			return mav;
		}
		
		List list = new ArrayList();
		for(int i =0;i < hps.length;i ++){
			list.add(hps[i]);
		}
		vo.put("list", list);		
		List samList = usrService.updateUsrList(vo);
		if (samList.size() > 0) {
			jsonMap.put("returnCd", "1");
			jsonMap.put("list", samList);
		} else {
			vo.put("mem_seq", Integer.toString(usrService.insertUsr(vo)));
			for(int i =0;i < hps.length;i ++){
				vo.put("hp", hps[i]);
				usrService.insertUsrHp(vo);	
			}
			
			jsonMap.put("returnCd", "0");
		}

		mav.addObject("map", jsonMap);
		
		return mav;
	}

	

	@RequestMapping
	public ModelAndView udtAdminUsr(@RequestParam Map vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		isAdminMember(req,res);
		ModelAndView mav = new ModelAndView();

		COMAVo codeVo = new COMAVo();
		// 가입사이트
		codeVo.setCode_p_no("05");
		mav.addObject("cd1List", comaService.coma104Q(codeVo));
		
		//등급
		codeVo.setCode_p_no("06");
		mav.addObject("cd2List", comaService.coma104Q(codeVo));

		mav.addObject("map", usrService.getUsr(vo));
		mav.addObject("cdList3", service.adminCode(vo));
		return mav;
	}

	@RequestMapping
	public ModelAndView updateUsr(@RequestParam Map vo, HttpServletRequest req,@RequestParam String[] hps,
			HttpServletResponse res) throws Exception {
		isAdminMember(req,res);
		ModelAndView mav = new ModelAndView("common/toJson");
		Map jsonMap = new HashMap();

		List list = new ArrayList();
		for(int i =0;i < hps.length;i ++){
			list.add(hps[i]);
		}
		vo.put("list", list);
		List samList = usrService.updateUsrList(vo);
		if (samList.size() > 0) {
			jsonMap.put("returnCd", "1");
			jsonMap.put("list", samList);
		} else {

			//기존 데이터 지우고
			usrService.deleteUsrHp(vo);
			//수정
			usrService.updateUsr(vo);
			//휴대폰 번호 추가
			for(int i =0;i < hps.length;i ++){
				vo.put("hp", hps[i]);
				usrService.insertUsrHp(vo);	
			}
			jsonMap.put("returnCd", "0");
		}
		
		mav.addObject("map", jsonMap);
		return mav;
	}
	
	@RequestMapping
	public ModelAndView main(@RequestParam Map vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		isAdminMember(req,res);
		ModelAndView mav = new ModelAndView();

		return mav;
	}
	
	@RequestMapping
	public ModelAndView admList(@RequestParam Map vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		isAdminMember(req,res);
		ModelAndView mav = new ModelAndView();
		// Map jsonMap = new HashMap();
		mav.addObject("list", service.admList(vo));
		// mav.addObject("cd1List", service.admList(vo));
		return mav;
	}
	
	@RequestMapping
	public ModelAndView deleteInfoAdm(@RequestParam Map vo, HttpServletRequest req,@RequestParam String[] del_chk,
			HttpServletResponse res) throws Exception {

		ModelAndView mav = new ModelAndView("/common/close");
		mav.addObject("redirect", "./usrList.do");
		
		for(int i =0;i < del_chk.length;i++){
		
			Map data = new HashMap();
			String[] spl = del_chk[i].split(",");
			data.put("adm_seq", spl[0]);
			data.put("mem_seq", spl[1]);
			usrService.deleteInfo(data);
		}
		
		mav.addObject("msg", "삭제되었습니다");
		
		return mav;
	}


	@RequestMapping
	public ModelAndView intAdmin(@RequestParam Map vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		isAdminMember(req,res);
		ModelAndView mav = new ModelAndView();
		COMAVo codeVo = new COMAVo();

		// 타입
		codeVo.setCode_p_no("07");
		mav.addObject("cd1List", comaService.coma104Q(codeVo));

		return mav;
	}

	@RequestMapping
	public ModelAndView insertAdmin(@RequestParam Map vo,@RequestParam String[] admin_nos,
			HttpServletRequest req, HttpServletResponse res) throws Exception {
		isAdminMember(req,res);
		ModelAndView mav = new ModelAndView("common/toJson");
		Map jsonMap = new HashMap();

		
		if(admin_nos.length==0){
			jsonMap.put("returnCd", "2");

			mav.addObject("map", jsonMap);
			
			return mav;
		}

		List list = new ArrayList();
		for(int i =0;i < admin_nos.length;i ++){
			list.add(admin_nos[i]);
		}
		vo.put("list", list);		
		List samList = service.samAdminList(vo);
		if (samList.size() > 0) {
			jsonMap.put("returnCd", "1");
			jsonMap.put("list", samList);
		} else {
			if (null == vo.get("roll1") || "".equals(vo.get("roll1"))) {
				vo.put("roll1", "N");
			}
			if (null == vo.get("roll2") || "".equals(vo.get("roll2"))) {
				vo.put("roll2", "N");
			}
			if (null == vo.get("roll3") || "".equals(vo.get("roll3"))) {
				vo.put("roll3", "N");
			}
			if (null == vo.get("roll4") || "".equals(vo.get("roll4"))) {
				vo.put("roll4", "N");
			}
			vo.put("adm_seq", Integer.toString(service.insertAdmin(vo)));
			for(int i =0;i < admin_nos.length;i ++){
				vo.put("admin_no", admin_nos[i]);
				service.insertAdmHp(vo);	
			}
			
			jsonMap.put("returnCd", "0");
		}
		mav.addObject("map", jsonMap);

		return mav;
	}

	@RequestMapping
	public ModelAndView udtUsr(@RequestParam Map vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		isAdminMember(req,res);
		ModelAndView mav = new ModelAndView("chkAdm/data/info/intAdmin");

		COMAVo codeVo = new COMAVo();
		// 타입
		codeVo.setCode_p_no("07");
		mav.addObject("cd1List", comaService.coma104Q(codeVo));
		mav.addObject("map", service.getAdminUsr(vo));
		mav.addObject("admHp", service.getAdmHp(vo));
		mav.addObject("udt", "U");

		return mav;
	}

	@RequestMapping
	public ModelAndView updateAdmin(@RequestParam Map vo,@RequestParam String[] admin_nos,
			HttpServletRequest req, HttpServletResponse res) throws Exception {
		isAdminMember(req,res);
		ModelAndView mav = new ModelAndView("common/toJson");
		Map jsonMap = new HashMap();
		if (null == vo.get("roll1") || "".equals(vo.get("roll1"))) {
			vo.put("roll1", "N");
		}
		if (null == vo.get("roll2") || "".equals(vo.get("roll2"))) {
			vo.put("roll2", "N");
		}
		if (null == vo.get("roll3") || "".equals(vo.get("roll3"))) {
			vo.put("roll3", "N");
		}
		if (null == vo.get("roll4") || "".equals(vo.get("roll4"))) {
			vo.put("roll4", "N");
		}

		service.updateAdmin(vo);
		service.deleteAdminHp(vo);
		
		for(int i =0;i < admin_nos.length;i ++){
			vo.put("admin_no", admin_nos[i]);
			service.insertAdmHp(vo);	
		}
		jsonMap.put("returnCd", "0");
		mav.addObject("map", jsonMap);

		return mav;
	}

	@RequestMapping
	public ModelAndView importExcel(@RequestParam Map vo,
			HttpServletRequest req, HttpServletResponse res) throws Exception {
		isAdminMember(req,res);
		ModelAndView mav = new ModelAndView();

		return mav;
	}

	@RequestMapping
	public ModelAndView importExcelPrc(@RequestParam Map vo,
			HttpServletRequest req,
			MultipartHttpServletRequest mRqst, HttpServletResponse res)
			throws Exception {
		isAdminMember(req,res);
		Map returnMap = new HashMap();

		ModelAndView mav = new ModelAndView("common/toJson");
		SMCommonUtil util = new SMCommonUtil();

		MultiValueMap mulitFileMap = mRqst.getMultiFileMap();
		String usr_file_path = "/WEB-INF/uploadExcel";
		
		COMAVo codeVo = new COMAVo();

		//사이트
		codeVo.setCode_p_no("05");
		List codeList1= comaService.coma104Q(codeVo);
		
		//등급
		codeVo.setCode_p_no("06");
		List codeList2= comaService.coma104Q(codeVo);

		//사이트
		Map<String,String> cMap1 = new HashMap();
		//등급
		Map<String,String> cMap2 = new HashMap();
		for(int i=0;i < codeList1.size();i++){
			Map data = (Map) codeList1.get(i);
			cMap1.put("V"+data.get("code"), data.get("code_no").toString());
		}
		for(int i=0;i < codeList2.size();i++){
			Map data = (Map) codeList2.get(i);
			cMap2.put("V"+data.get("code"), data.get("code_no").toString());
		}
		
		String[] files = { "file" };
		Map fileMap = util.getFileInfo(mulitFileMap, mRqst.getSession()
				.getServletContext().getRealPath(""), usr_file_path, false,
				files);

		if ("Y".equals((String) fileMap.get("error_yn"))) {
			// 에러처리
		}
		FastDateFormat sdf = FastDateFormat.getInstance("yyyyMMddhhmmss", Locale.getDefault());
		String nowDate = sdf.format(Calendar.getInstance().getTime());
		

		int iAddCnt = 0;

		int iAddFail = 0;
		String sFailMsg = "";

		int iSamUserCnt = 0;
		String sSamMsg = "";

		if (fileMap.get("files") != null) {
			List fileList = (List) fileMap.get("files");
			Map fMap = (Map) fileList.get(0);

			returnMap.put("file_nm", fMap.get("files_nm"));
			returnMap.put("p_file_nm", fMap.get("file"));
			returnMap.put("p_file_sz", fMap.get("files_sz"));

			// poi 파일 읽고 등록하기
			String FilePath = mRqst.getSession().getServletContext()
					.getRealPath(fMap.get("file").toString());
			POIFSFileSystem excel = new POIFSFileSystem(new FileInputStream(
					FilePath));
			HSSFWorkbook workBook = new HSSFWorkbook(excel);
			HSSFSheet sheet = null;
			HSSFRow row = null;
			HSSFCell cell = null;

			// 생성된 워크북을 이용하여 시트 수만큼 돌면서 엑셀 시트 하나씩을 생성합니다.
			// int sheetNum = workBook.getNumberOfSheets();
			int sheetNum = 1;
			for (int k = 0; k < sheetNum; k++) {
				// System.out.println("Sheet Num : " + k);
				// System.out.println("Sheet Name : " +
				// workBook.getSheetName(k));
				sheet = workBook.getSheetAt(k);

				// 생성된 시트를 이용하여 그 행의 수만큼 돌면서 행을 하나씩 생성합니다.
				int rows = sheet.getPhysicalNumberOfRows();
				for (int r = 1; r < rows; r++) {
					row = sheet.getRow(r);
					if(null !=row){
						Map insertMap = new HashMap();
						insertMap.put("adm_seq", vo.get("adm_seq"));

						// 역시나 생성된 행을 이용하여 그 셀의 수만큼 돌면서 셀을 하나씩 생성합니다.
						int cells = row.getPhysicalNumberOfCells();
						for (int c = 0; c < cells; c++) {
							cell = row.getCell(c);
							if (c == 0) {
								if(cell != null){
									insertMap.put("nick", cell.toString());
								}
								
							} else if (c == 1) {
								if(cell != null){
									insertMap.put("hp",
											cell.toString().replaceAll("-", ""));	
								}
							} else if (c == 2) {
								if(cell == null){
									insertMap.put("user_type", "");
								}else{
									if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
										insertMap.put("user_type", cMap2.get("V"+Integer
												.toString(Integer.parseInt( String.valueOf(Math.round(cell.getNumericCellValue()) )
														))));
									} else {
										insertMap.put("user_type", cMap2.get("V"+cell.toString()));
									}								
								}
							} else if (c == 3) {
								if(cell == null){
									insertMap.put("con_site", "");
								}else{
									if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
										insertMap.put("con_site", cMap1.get("V"+Integer
												.toString(Integer.parseInt( String.valueOf(Math.round(cell.getNumericCellValue()) )
														))));
									} else {
										insertMap.put("con_site", cMap1.get("V"+cell.toString()));
									}
								}
								
							} else if (c == 4) {
								if(cell == null){
									insertMap.put("sec_etc", "");
								}else{
									insertMap.put("sec_etc", cell.toString().replaceAll("\n", ", "));
								}
								
							} else if (c == 5) {
								if(cell == null){
									insertMap.put("etc", "");
								}else{
									insertMap.put("etc", cell.toString().replaceAll("\n", ", "));
								}
								
							} else if (c == 6) {
								if(cell == null){
									insertMap.put("reg_dt", nowDate);								
								}else{
									insertMap.put("reg_dt", cell.toString()
											.replaceAll("-", "")+"010101");
								}
							}
						}

						if (insertMap.get("hp") != null && !	"".equals(insertMap.get("hp").toString().trim()) ) {
							String hps = insertMap.get("hp").toString().replaceAll("\n", "").replaceAll(" ", "");
							String[] arHp = hps.split(",");
							String mem_seq ="";
							for(int j = 0;j < arHp.length;j++){

								insertMap.put("hp", arHp[j]);
								// 기존에 데이터가 있는지 체크
								int iSamUser = usrService.updateUsrCnt(insertMap);
								
								if (iSamUser == 0) {
									if("".equals(mem_seq)){
										mem_seq = Integer.toString( usrService.insertUsr(insertMap));
										insertMap.put("mem_seq", mem_seq);
									}
									
									// 신규등록
									try {
										usrService.insertUsrHp(insertMap);
										iAddCnt++;
									} catch (Exception e) {
										// TODO: handle exception
										iAddFail++;
										if (!"".equals(sFailMsg)) {
											sFailMsg += ",";
										}
										sFailMsg += r + "열 " + insertMap.get("hp");
									}
								} else {
									// 기존에 있는 사람
									iSamUserCnt++;
									if (!"".equals(sSamMsg)) {
										sSamMsg += ",";
									}
									sSamMsg += r + "열 " + insertMap.get("hp");

								}
							}
						}
					}
					
				}
			}
		}
		
		usrService.updateNic();
		

		Map jsonMap = new HashMap();
		jsonMap.put("iAddCnt", iAddCnt);
		jsonMap.put("iAddFail", iAddFail);
		jsonMap.put("sFailMsg", sFailMsg);
		jsonMap.put("iSamUserCnt", iSamUserCnt);
		jsonMap.put("sSamMsg", sSamMsg);

		mav.addObject("map", jsonMap);
		return mav;
	}

}
